﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Community.IService;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Core;
using FantastPlatform.Community.IMode;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Framework.IService;
using FantastPlatform.Community.Model;
using System.IO;

namespace FantastPlatform.Community.UI.Service
{
    public partial class HouseDistrictService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            IHouseDistrictService HdService = ServiceFactory.CreateService<IHouseDistrictService>();
            IOrganizationService OgService = ServiceFactory.CreateService<IOrganizationService>();
            IOrganization org = LoginEmployee.EmployeePosts[0].Post.Organization;
            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true };
            group.Conditions.Add(enableCondition);

            IHouseDistrict housedistrict = new FantastPlatform.Community.Model.HouseDistrict();
            IList<Sort> sorts = new List<Sort>();
            switch (Action)
            {
                case "Add":
                    string data = Data;
                    HouseDistrictView view = (HouseDistrictView)JsonToEntity<HouseDistrictView>(RepairString(data));
                    if (view != null)
                    {
                        string[] arrStreet = view.StreetId.Split(',');
                        string[] arrResponsibilityArea = view.Community.Split(',');
                        string[] arrStation = view.PoliceStation.Split(',');
                        housedistrict.Id = view.Id;
                        housedistrict.Code = arrResponsibilityArea[1] + arrStreet[1] + AddressToCode(view.Number) + "000000";
                        housedistrict.Name = view.Name;
                        housedistrict.Phone = view.Phone;
                        housedistrict.Address = view.Number;
                        housedistrict.Station = new FantastPlatform.Framework.Model.Organization();
                        housedistrict.Station.Id = Int32.Parse(arrStation[0]);
                        housedistrict.Street = new FantastPlatform.Framework.Model.Street();
                        housedistrict.Street.Id = Int32.Parse(arrStreet[0]);
                        housedistrict.ResponsibilityArea = new FantastPlatform.Framework.Model.Organization();
                        housedistrict.ResponsibilityArea.Id = Int32.Parse(arrResponsibilityArea[0]);
                        //housedistrict.latitude = view.latitude;
                        //housedistrict.longitude = view.longitude;
                        housedistrict.Concierge = view.Concierge;
                        housedistrict.Description = view.Description;
                        housedistrict.CreateDate = view.CreateDate;
                        housedistrict.PoliceMan = LoginEmployee;
                        housedistrict.Description = view.Description;
                    }
                    housedistrict.Enable = true;
                    if (housedistrict.Id == 0)
                    {
                        HdService.Create(housedistrict);
                        ReturnSuccessMessage("保存成功");
                    }
                    else
                    {
                        housedistrict.ModifyDate = DateTime.Now;
                        IHouseDistrict oldHousedistrict = HdService.Get(housedistrict.Id);
                        housedistrict.CreateDate = oldHousedistrict.CreateDate;
                        housedistrict.PoliceMan = oldHousedistrict.PoliceMan;
                        HdService.Update(housedistrict);
                        ReturnSuccessMessage("更新成功");
                    }
                    break;

                case "Search":
                    int total;
                    object[] hd;
                    if (LoginEmployee != null)
                    {
                        if (LoginEmployee.User != null)
                        {
                            IList<IRole> roleList = LoginEmployee.User.Roles;
                            List<string> roles = new List<string>();
                            foreach (IRole role in roleList)
                            {
                                roles.Add(role.Name);
                            }
                            if (roles.Contains("社区一级管理员") || roles.Contains("管理员"))
                            {

                            }
                            else if (roles.Contains("社区二级管理员"))
                            {
                                group.Conditions.Add(new Condition() { Field = "PoliceMan.EmployeePosts.Post.Organization.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = org.Id });
                            }
                            else
                            {
                                group.Conditions.Add(new Condition() { Field = "PoliceMan.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = LoginEmployee.Id });
                            }
                        }
                    }
                    IList<IHouseDistrict> list = HdService.Search(group, null, PageSize, SelfPage, out total);
                    hd = (from p in list
                          select new
                        {
                            Id = p.Id,
                            Code = p.Code,
                            Name = p.Name,
                            Address =  p.Street.Name + p.Address,
                            CreateDate = p.CreateDate,
                            Description = p.Description,
                            Concierge = p.Concierge,
                            Phone = p.Phone,
                            PoliceMan = p.PoliceMan.Name
                        }).OrderByDescending(p => p.CreateDate).ThenBy(p => p.Id).ToArray();
                    ReturnList(total, hd);
                    break;

                case "Get":
                    housedistrict = HdService.Get(Id);
                    object objhousedistrict = (new
                                     {
                                         Id = housedistrict.Id,
                                         Name = housedistrict.Name,
                                         Phone = housedistrict.Phone,
                                         PoliceStationName = housedistrict.Station.Id + "," + housedistrict.Station.Code + "|" + housedistrict.Station.Name,
                                         CommunityName = housedistrict.ResponsibilityArea.Id + "," + housedistrict.ResponsibilityArea.Code + "|" + housedistrict.ResponsibilityArea.Name,
                                         StreetName = housedistrict.Street.Id + "," + housedistrict.Street.Code+ "|" + housedistrict.Street.Name,
                                         Number = housedistrict.Address,
                                         //latitude = housedistrict.latitude,
                                         //longitude = housedistrict.longitude,
                                         Concierge = housedistrict.Concierge,
                                         Description = housedistrict.Description,
                                         CreateDate = housedistrict.CreateDate,
                                         PoliceMan = housedistrict.PoliceMan.Name
                                     });
                    ReturnObj(objhousedistrict);
                    break;

                case "Delete":
                    if (string.IsNullOrEmpty(Data))
                    {
                        throw new Exception("传入的ID为空");
                    }
                    List<int> idList = new List<int>();
                    string[] idStrList = Data.Split(',');
                    foreach (string id in idStrList)
                    {
                        idList.Add(int.Parse(id));
                    }
                    HdService.Delete(idList);
                    ReturnSuccessMessage("删除成功");
                    break;
                case "SearchByCondition":
                    int totalCount = 0;
                    string Searchjson = RepairString(Data);
                    housedistrict = JsonToEntity<FantastPlatform.Community.Model.HouseDistrict>(Searchjson);
                    IList<IHouseDistrict> housedistrictList1 = HdService.SearchByCondition(housedistrict.Name, housedistrict.Address, LoginEmployee.Id);
                    var objhousedistrict1 = (from n in housedistrictList1
                                             select new
                                             {
                                                 Id = n.Id,
                                                 Code = n.Code,
                                                 Name = n.Name,
                                                 Address = n.Street.Name + n.Address,
                                                 CreateDate = n.CreateDate.ToString(),
                                                 Description = n.Description,
                                                 Concierge = n.Concierge,
                                                 Phone = n.Phone,
                                                 PoliceMan = n.PoliceMan.Name
                                             });
                    var objList = objhousedistrict1.ToList();
                    ReturnList(objList.Count, objhousedistrict1);
                    break;

                case "GetStreet":
                    string CommunityId = "";
                    if (!string.IsNullOrEmpty(Request["parentCode"]))
                    {
                        CommunityId = Request["parentCode"].Split(',')[0]; ;
                        group.Conditions.Add(new Condition() { Field = "PoliceMan.EmployeePosts.Post.Organization.Id", Relation = Relations.And, Type = typeof(Int32).FullName, Value1 = CommunityId });

                    }
                    string code = "";
                    if (!string.IsNullOrEmpty(Request["code"]))
                    {
                        code = Request["code"];
                    }
                    totalCount = 0;
                    IPoliceStreetService policestreetService = ServiceFactory.CreateService<IPoliceStreetService>();
                    IList<IStreet> policeStreetList = policestreetService.SearchStreet(code, group, PageSize, SelfPage, out totalCount);
                    object[] objArr = (from o in policeStreetList
                                       select new
                                       {
                                           Id = o.Id + "," + o.Code,
                                           Code = o.Code,
                                           Name = o.Name
                                       }).ToArray();

                    ReturnList(PageSize, totalCount, objArr);
                    break;
                case "GetPoliceStation":
                    int StationCount = 0;
                    code = "";
                    if (!string.IsNullOrEmpty(Request["code"]))
                    {
                        code = Request["code"];
                    }
                    Condition PoliceStationCondition = new Condition() { Type = typeof(string).FullName, Field = "Name", Value1 = code + "%派出所", Comparison = Comparisons.Like, Relation = Relations.And };
                    group.Conditions.Add(PoliceStationCondition);

                    if (LoginEmployee != null)
                    {
                        if (LoginEmployee.User != null)
                        {
                            IList<IRole> roleList = LoginEmployee.User.Roles;
                            List<string> roles = new List<string>();
                            foreach (IRole role in roleList)
                            {
                                roles.Add(role.Name);
                            }
                            if (roles.Contains("社区一级管理员") || roles.Contains("管理员"))
                            {
                                IList<IOrganization> organizationList = OgService.Search(group, sorts, PageSize, SelfPage, out StationCount);
                                var objStationList = (from sa in organizationList
                                                      select new
                                                      {
                                                          Id = sa.Id+ "," +sa.Code,
                                                          Code = sa.Code,
                                                          Name = sa.Name
                                                      }).ToArray();
                                ReturnList(StationCount, objStationList);
                            }
                            else if (roles.Contains("社区二级管理员"))
                            {
                                group.Conditions.Add(new Condition()
                                {
                                    Field = "Id",
                                    Relation = Relations.And,
                                    Type = typeof(Int32).FullName,
                                    Value1 = (from p in LoginEmployee.EmployeePosts
                                              where p.Post.Organization.Name.EndsWith("派出所") && p.Enable == true
                                              select
                                                   p.Post.Organization.Id
                                              ).FirstOrDefault()
                                });
                                IList<IOrganization> organizationList = OgService.Search(group, sorts, PageSize, SelfPage, out StationCount);
                                var objStationList = (from sa in organizationList
                                                      select new
                                                      {
                                                          Id = sa.Id + "," + sa.Code,
                                                          Code = sa.Code,
                                                          Name = sa.Name
                                                      }).ToArray();
                                ReturnList(StationCount, objStationList);
                            }
                            else
                            {
                                objArr = (from p in LoginEmployee.EmployeePosts
                                          where p.Post.Organization.Name.EndsWith("责任区") && p.Enable == true
                                          select new
                                          {
                                              Id = p.Post.Organization.Parent.Id+ "," + p.Post.Organization.Parent.Code,
                                              Code = p.Post.Organization.Parent.Code,
                                              Name = p.Post.Organization.Parent.Name
                                          }).ToArray();
                                ReturnList(objArr.Length, objArr);
                            }
                        }
                    }

                    break;
                case "GetCommunity":
                    string PoliceStationId = "";
                    if (!string.IsNullOrEmpty(Request["parentCode"]))
                    {
                        PoliceStationId = Request["parentCode"].Split(',')[0];
                        Condition PoliceCondition = new Condition() { Type = typeof(int).FullName, Field = "Parent.Id", Value1 = PoliceStationId, Relation = Relations.And };
                        group.Conditions.Add(PoliceCondition);

                    }
                    code = "";
                    if (!string.IsNullOrEmpty(Request["code"]))
                    {
                        code = Request["code"];
                    }
                    int CommunityCount = 0;
                    Condition CommunityCondition = new Condition() { Type = typeof(string).FullName, Field = "Name", Value1 = code + "%责任区", Comparison = Comparisons.Like, Relation = Relations.And };
                    group.Conditions.Add(CommunityCondition);

                    if (LoginEmployee != null)
                    {
                        if (LoginEmployee.User != null)
                        {
                            IList<IRole> roleList = LoginEmployee.User.Roles;
                            List<string> roles = new List<string>();
                            foreach (IRole role in roleList)
                            {
                                roles.Add(role.Name);
                            }
                            if (roles.Contains("社区一级管理员") || roles.Contains("管理员"))
                            {
                                IList<IOrganization> communityList = OgService.Search(group, sorts, PageSize, SelfPage, out CommunityCount);
                                var objcommunityList = (from c in communityList
                                                        select new
                                                        {
                                                            Id = c.Id + "," + c.Code,
                                                            Code = c.Code,
                                                            Name = c.Name
                                                        }).ToArray();
                                ReturnList(CommunityCount, objcommunityList);
                            }
                            else if (roles.Contains("社区二级管理员"))
                            {
                                group.Conditions.Add(new Condition()
                                {
                                    Field = "Parent.Id",
                                    Relation = Relations.And,
                                    Type = typeof(Int32).FullName,
                                    Value1 = (from p in LoginEmployee.EmployeePosts
                                              where p.Post.Organization.Name.EndsWith("派出所") && p.Enable == true
                                              select
                                                   p.Post.Organization.Id
                                              ).FirstOrDefault()
                                });
                                IList<IOrganization> communityList = OgService.Search(group, sorts, PageSize, SelfPage, out CommunityCount);
                                var objcommunityList = (from c in communityList
                                                        select new
                                                        {
                                                            Id = c.Id + "," + c.Code,
                                                            Code = c.Code,
                                                            Name = c.Name
                                                        }).ToArray();
                                ReturnList(CommunityCount, objcommunityList);
                            }
                            else
                            {
                                objArr = (from p in LoginEmployee.EmployeePosts
                                          where p.Post.Organization.Name.EndsWith("责任区") && p.Enable == true
                                          select new
                                          {
                                              Id = p.Post.Organization.Id + "," + p.Post.Organization.Code,
                                              Code = p.Post.Organization.Code,
                                              Name = p.Post.Organization.Name
                                          }).ToArray();
                                ReturnList(objArr.Length, objArr);
                            }
                        }
                    }

                    break;
                case "AddHouserDestrictImage":

                    data = Data;
                    if (String.IsNullOrEmpty(data))
                    {
                        throw new Exception("传入的数据为空");
                    }
                    HouseDistrictImageView imageView = JsonToEntity<HouseDistrictImageView>(RepairString(data));
                    totalCount = 0;

                    IHouseDistrictImageService houserDestrictImageService = ServiceFactory.CreateService<IHouseDistrictImageService>();
                    IHouseDistrictImage houseDestrictImage = houserDestrictImageService.Get(imageView.Id);
                    if (houseDestrictImage == null)
                    {
                        houseDestrictImage = new HouseDistrictImage();
                        houseDestrictImage.Name = imageView.Name;
                        houseDestrictImage.Description = imageView.Description;
                        houseDestrictImage.HouseDistrict = new HouseDistrict() { Id = imageView.HouseId };
                        houseDestrictImage.ImagePath = imageView.ImageUrl;
                        houserDestrictImageService.Create(houseDestrictImage);
                        ReturnSuccessMessage("图片信息添加成功");
                    }
                    else
                    {
                        //增加判断，在更新时是否重新上传图片，重新上传图片则进行旧图片的删除。
                        //  ICaseCallBack caseCallBackOld = service.Get(caseCallBack2.Id);
                        if (!imageView.ImageUrl.Equals(houseDestrictImage.ImagePath))
                        {
                            //以下删除旧图片功能于2009/09/07增加 By杨雄
                            //找到未更新前的警种图片，并删除
                            string imgname = houseDestrictImage.ImagePath;
                            string imgurl = Server.MapPath("../upload/") + imgname;
                            if (File.Exists(imgurl))
                            {
                                File.Delete(imgurl);
                            }
                        }
                        houseDestrictImage.Name = imageView.Name;
                        houseDestrictImage.Description = imageView.Description;
                        houseDestrictImage.ImagePath = imageView.ImageUrl;
                        houserDestrictImageService.Update(houseDestrictImage);
                        ReturnSuccessMessage("图片信息更新成功");
                    }
                    break;
                case "GetHouserDestrictImage":
                    houserDestrictImageService = ServiceFactory.CreateService<IHouseDistrictImageService>();
                    houseDestrictImage = houserDestrictImageService.Get(Id);
                    if (houseDestrictImage == null)
                    {
                        houseDestrictImage = new HouseDistrictImage();
                    }
                    object objImage = new
                    {
                        Id = houseDestrictImage.Id,
                        Name = houseDestrictImage.Name,
                        Description = houseDestrictImage.Description,
                        ImageUrl = houseDestrictImage.ImagePath,
                        HouseId = houseDestrictImage.HouseDistrict.Id
                    };
                    ReturnObj(objImage);
                    break;
                case "SearchImage":
                    houserDestrictImageService = ServiceFactory.CreateService<IHouseDistrictImageService>();
                    group.Conditions.Add(new Condition() { Type = typeof(int).FullName, Field = "HouseDistrict.Id", Value1 = Id });

                    IList<IHouseDistrictImage> imageList = houserDestrictImageService.Search(group, null, PageSize, SelfPage, out totalCount);
                    object[] imageObj = (from l in imageList
                                         select new
                                         {
                                             Id = l.Id,
                                             Name = l.Name,
                                             Description = l.Description,
                                             ImagePath = l.ImagePath
                                         }).ToArray();
                    ReturnList(totalCount, imageObj);
                    break;
                case "DeleteImage":
                    List<int> ids = new List<int>();
                    string[] idArray = Data.Split(',');
                    foreach (string id in idArray)
                    {
                        ids.Add(int.Parse(id));
                    }
                    houserDestrictImageService = ServiceFactory.CreateService<IHouseDistrictImageService>();
                    houserDestrictImageService.Delete(ids);
                    ReturnSuccessMessage("移除记录成功");
                    break;

            }

        }
        private string AddressToCode(string address)
        {
            string code = string.Empty;
            Random rd = new Random();
            string rdStr = rd.Next(9999).ToString("D6");
            try
            {
                string[] nums = address.Split('组');
                if (nums.Length > 1)
                {
                    int num1 = Convert.ToInt32(nums[0]);
                    int num2 = Convert.ToInt32(nums[1].Split('号')[0]);
                    rdStr = num1.ToString("D2") + num2.ToString("D4");
                }
                else
                {
                    nums = address.Split('号');
                    int num1 = Convert.ToInt32(nums[0]);
                    int num2 = Convert.ToInt32(nums[1].Split('附')[0]);
                    rdStr = num1.ToString("D4") + num2.ToString("D2");
                }
            }
            catch (Exception ex)
            {
            }
            return rdStr;
        }

        public class HouseDistrictView
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string PoliceMan { get; set; }
            public string Phone { get; set; }
            public string Concierge { get; set; }
            public string Description { get; set; }
            //public float longitude { get; set; }
            //public float latitude { get; set; }
            public string PoliceStation { get; set; }
            public string StreetId { get; set; }
            public string Community { get; set; }
            public string Number { get; set; }
            public DateTime? CreateDate { get; set; }
        }
        public class HouseDistrictImageView
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public int HouseId { get; set; }
            public string ImageUrl { get; set; }
        }
    }
}